﻿using FairyGUI;
public class UI_Login : Window
{
    public GTextInput m_inputUser;
    public GTextInput m_inputPassWd;
    public GButton m_checkRePassWd;
    public GButton m_checkAuto;
    public GButton m_btnRegister;
    public GButton m_btnConfirm;

    protected override void OnInit()
    {
        base.OnInit();
        this.contentPane = UIManager.Instance.LoadComponent("Login", "UILogin");
        m_inputUser = (GTextInput)this.contentPane.GetChild("inputUser");
        m_inputPassWd = (GTextInput)this.contentPane.GetChild("inputPassWd");
        m_btnRegister = (GButton)this.contentPane.GetChild("btnRegister");
        m_btnConfirm = (GButton)this.contentPane.GetChild("btnConfirm");
        m_checkRePassWd = (GButton)this.contentPane.GetChild("checkRePassWd");
        m_checkAuto = (GButton)this.contentPane.GetChild("checkAutoLogin");
        //登录
        m_btnConfirm.onClick.Add(() =>
        {
            string user = m_inputUser.text;
            string passwd = m_inputPassWd.text;
            if (user.Length == 0)
            {
                UI_Message panel = UIManager.Instance.ShowWindow<UI_Message>();
                panel.Message("请输入账号!");
                return;
            }
            if (passwd.Length == 0)
            {
                UI_Message panel = UIManager.Instance.ShowWindow<UI_Message>();
                panel.Message("请输入密码!");
                return;
            }
            LoginAccount(user, passwd);
        });
        //注册
        m_btnRegister.onClick.Add(() =>
        {
            Hide();
            UIManager.Instance.ShowWindow<UI_Register>();
        });
    }
    
    protected override void OnShown()
    {
        base.OnShown();
        InitUIData();
    }

    private void LoginAccount(string user, string passwd)
    {
        if (!AccountMgr.Instance.LoginAccount(user, passwd, m_checkRePassWd.selected, m_checkAuto.selected))
        {
            UI_Message panel = UIManager.Instance.ShowWindow<UI_Message>();
            panel.Message("登录失败,账号或密码错误!");
            return;
        }
        Hide();
        if (AccountMgr.Instance.lastServerId != 0)
        {
            UIManager.Instance.ShowWindow<UI_ServerSelect>();
            return;
        }
        UIManager.Instance.ShowWindow<UI_ServerList>();
    }

    private void InitUIData()
    {
        AccountInfo accountInfo = AccountMgr.Instance.accountInfo;
        if (accountInfo.lastAccount == "")
            return;
        m_checkAuto.selected = accountInfo.autoLogin;
        m_checkRePassWd.selected = accountInfo.rePassword;
        m_inputUser.text = accountInfo.lastAccount;
        if (accountInfo.rePassword)
            m_inputPassWd.text = accountInfo.accounts[accountInfo.lastAccount];

        if (accountInfo.autoLogin)
            LoginAccount(accountInfo.lastAccount, m_inputPassWd.text);
    }
}
